package Volume2.ch1;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

/**
 * 1. 从迭代到流到操作
 * @Auther jacob
 * @Date 2020/8/8 12:29
 */
public class CountLongWords {
    public static void main(String[] args) throws IOException {
        String contents = new String(Files.readAllBytes(
                Paths.get("src/Volume2/ch1/words.txt")), StandardCharsets.UTF_8);
        List<String> words = Arrays.asList(contents.split("\n"));

        // 传统遍历方法
        long count = 0;
        long beginTime = System.nanoTime();
        for (String w : words) {
            if (w.length() > 5){
                count++;
            }
        }
        System.out.println("传统遍历 count = " + count + ", times = " + (System.nanoTime() - beginTime));

        // 流操作
        beginTime = System.nanoTime();
        count = words.stream().filter(w->w.length()>5).count();
        System.out.println("流操作 count = " + count + ", times = " + (System.nanoTime() - beginTime));

        // 流操作
        beginTime = System.nanoTime();
        count = words.parallelStream().filter(w->w.length()>5).count();
        System.out.println("并行流操作 count = " + count + ", times = " + (System.nanoTime() - beginTime));

    }
}
